﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;

namespace INSTA.MusiqueStore.DAL
{
    public static  class TestEmail
    {
        public static bool exits;
        public static bool invalid = false;
        public static string _Email;

        /// <summary>
        /// Proprété permetant de verifier la validité de la boite mail.
        /// </summary>
        /// <param name="email"></param>
        /// <returns>true si l'email est au bon format et false sinon</returns>
        public static  bool ValidationEmail(string email)
        {
            invalid = false;
            if (String.IsNullOrEmpty(email))
                return false;

            // Use IdnMapping class to convert Unicode domain names.
            try
            {
                email = Regex.Replace(email , @"(@)(.+)$",DomainMapper,
                                      RegexOptions.None, TimeSpan.FromMilliseconds(200));
            }
            catch (RegexMatchTimeoutException)
            {
                return false;
            }

            if (invalid)
                return false;

            // Return true if strIn is in valid e-mail format.
            try
            {
                return Regex.IsMatch(email ,
                      @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                      @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                      RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
            }
            catch (RegexMatchTimeoutException)
            {
                return false;
            }
        }
    


  public  static string DomainMapper(Match match)
   {
      // IdnMapping class with default property values.
      IdnMapping idn = new IdnMapping();

      string domainName = match.Groups[2].Value;
      try {
         domainName = idn.GetAscii(domainName);
      }
      catch (ArgumentException) {
         invalid = true;      
      }      
      return match.Groups[1].Value + domainName;
   }


   /// <summary>
   /// Propriété permetant de verifier si l'email existe déja dans la BD.
   /// </summary>
   /// <param name="email"></param>
   /// <returns></returns>
   public static bool EmailExists(string email)
   {
       var c = new MusiqueStoreEntities();
       var a = (from Client in c.Clients
                where Client.Email == email
                select Client).ToList();

       if(a.Count==0)
       {
           exits = false;
       }
       else
       {
           exits = true;
       }
      
       return exits;
   }

    
    
    
    }
}